package com.example.users.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.users.domain.Role;
import com.example.users.service.RoleService;
import com.example.users.common.PageResponse;
import com.example.users.common.PageUtil;
import com.example.users.common.ApiResponse;
import com.example.users.common.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

@RestController
@RequestMapping("/api/roles")
public class RoleController {

    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping
    public ApiResponse<PageResponse<Role>> list(@RequestParam(defaultValue = "1") long page,
                                  @RequestParam(defaultValue = "10") long size,
                                  @RequestParam(required = false) String keyword,
                                  @RequestParam(required = false, defaultValue = "id") String sortBy,
                                  @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        QueryWrapper<Role> qw = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            qw.lambda().like(Role::getName, keyword).or().like(Role::getCode, keyword);
        }
        if ("name".equalsIgnoreCase(sortBy)) {
            qw.orderBy(true, "asc".equalsIgnoreCase(sortOrder), "name");
        } else if ("code".equalsIgnoreCase(sortBy)) {
            qw.orderBy(true, "asc".equalsIgnoreCase(sortOrder), "code");
        } else {
            qw.orderBy(true, "asc".equalsIgnoreCase(sortOrder), "id");
        }
        Page<Role> result = roleService.page(Page.of(page, size), qw);
        return ApiResponse.success(PageUtil.toResponse(result));
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> detail(@PathVariable Long id) {
        Role role = roleService.getById(id);
        return ResponseEntity.ok(role);
    }

    @PostMapping
    public ApiResponse<?> create(@Validated(com.example.users.validation.groups.Create.class) @RequestBody Role role) {
        role.setId(null);
        boolean ok = roleService.save(role);
        return ApiResponse.success(ok ? role : null);
    }

    @PutMapping("/{id}")
    public ApiResponse<?> update(@PathVariable Long id, @Validated(com.example.users.validation.groups.Update.class) @RequestBody Role role) {
        role.setId(id);
        boolean ok = roleService.updateById(role);
        return ApiResponse.success(ok ? role : null);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> delete(@PathVariable Long id) {
        boolean ok = roleService.removeById(id);
        return ApiResponse.success(ok);
    }
}


